

package com.example.project.frag_chart;


import android.graphics.Bitmap;
import android.graphics.Color;
import android.text.SpannableString;
import android.view.View;

import androidx.fragment.app.Fragment;

import com.android.volley.VolleyError;
import com.example.project.R;
import com.example.project.bean.BarChartItemBean;
import com.example.project.db.DBManager;
import com.example.project.volley.ConstantUtil;
import com.example.project.volley.Params;
import com.example.project.volley.VolleyInterface;
import com.example.project.volley.VolleyRequest;
import com.github.mikephil.charting.animation.Easing;
import com.github.mikephil.charting.charts.PieChart;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.BarData;
import com.github.mikephil.charting.data.BarDataSet;
import com.github.mikephil.charting.data.BarEntry;
import com.github.mikephil.charting.data.PieData;
import com.github.mikephil.charting.data.PieDataSet;
import com.github.mikephil.charting.data.PieEntry;
import com.github.mikephil.charting.formatter.PercentFormatter;
import com.github.mikephil.charting.interfaces.datasets.IBarDataSet;
import com.github.mikephil.charting.utils.ColorTemplate;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * A simple {@link Fragment} subclass.
 */
public class IncomChartFragment extends BaseChartFragment {
    int kind = 1;
    float maxMoney;
    PieChart mPieChart;


    @Override
    public void onResume() {
        super.onResume();
        loadData(year,month,kind);
        set();
    }


//    @Override
//    public void setDate(int year, int month) {
//        super.setDate(year, month);
//        loadData(year,month,kind);
//    }

    //获取这个月的最大金额
    private void volleyMonthMax(String year,String month,String kind,String mainId) {
        VolleyInterface vif=null;
        VolleyRequest.RequesetPost( ConstantUtil.MONTHSR, "MonthMaxIn", Params.MonthMax(year,month,kind,mainId),new VolleyInterface( getContext() ){
            @Override
            public void onMySuccess(String jsonStr) {
                maxMoney=Float.parseFloat( jsonStr );
                float max = (float) Math.ceil(maxMoney);   // 将最大金额向上取整
                //        设置y轴
                YAxis yAxis_right = barChart.getAxisRight();
                yAxis_right.setAxisMaximum(max);  // 设置y轴的最大值
                yAxis_right.setAxisMinimum(0f);  // 设置y轴的最小值
                yAxis_right.setEnabled(false);  // 不显示右边的y轴

                YAxis yAxis_left = barChart.getAxisLeft();
                yAxis_left.setAxisMaximum(max);
                yAxis_left.setAxisMinimum(0f);
                yAxis_left.setEnabled(false);

                //        设置不显示图例
                Legend legend = barChart.getLegend();
                legend.setEnabled(false);
            }
            @Override
            public void onMyError(VolleyError error) {
            }
            @Override
            public void onImageSuccess(Bitmap bitmap) {
            }
        });
    }

    //获取这个月每天的支出总金额
    private void volleyDayNum(String year,String month,String kind,String mainId) {
        VolleyInterface vif=null;
        VolleyRequest.RequesetPost( ConstantUtil.MONTHSR, "DayNums", Params.DayNums(year,month,kind,mainId),new VolleyInterface( getContext() ){
            @Override
            public void onMySuccess(String jsonStr) {
                List<IBarDataSet> sets = new ArrayList<>();
                JSONArray jsonArray = null;
                // 初始化list数组对象
                ArrayList<BarChartItemBean> list = new ArrayList<>();
                try {
                    jsonArray = new JSONArray( jsonStr );
                    for (int j = 0; j < jsonArray.length(); j++) {
                        JSONObject juser = jsonArray.getJSONObject( j );
                        BarChartItemBean barChartItemBean = new BarChartItemBean();
                        barChartItemBean.setYear( Integer.parseInt( juser.getString( "year" ) ) );
                        barChartItemBean.setMonth( Integer.parseInt( juser.getString( "month" ) ) );
                        barChartItemBean.setDay( Integer.parseInt( juser.getString( "day" ) ) );
                        barChartItemBean.setSummoney( Float.parseFloat( juser.getString( "sum" ) ) );
                        list.add( barChartItemBean );
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                if (list.size() == 0) {
                    barChart.setVisibility(View.GONE);
                    chartTv.setVisibility(View.VISIBLE);
                }else{
                    barChart.setVisibility(View.VISIBLE);
                    chartTv.setVisibility(View.GONE);
//            设置有多少根柱子
                    List<BarEntry> barEntries1 = new ArrayList<>();
                    for (int i = 0; i < 31; i++) {
//                初始化每一根柱子，添加到柱状图当中
                        BarEntry entry = new BarEntry(i+1, 0.0f);
                        barEntries1.add(entry);
                    }
                    for (int i = 0; i < list.size(); i++) {
                        BarChartItemBean itemBean = list.get(i);
                        int day = itemBean.getDay();   //获取日期
                        // 根据天数，获取x轴的位置
                        int xIndex = day-1;
                        BarEntry barEntry = barEntries1.get(xIndex);
                        barEntry.setY(itemBean.getSummoney());
                    }
                    BarDataSet barDataSet1 = new BarDataSet(barEntries1, "");
                    barDataSet1.setValueTextColor(Color.BLACK); // 值的颜色
                    barDataSet1.setValueTextSize(8f); // 值的大小
                    barDataSet1.setColor(Color.parseColor("#006400")); // 柱子的颜色

                    // 设置柱子上数据显示的格式
//            barDataSet1.setValueFormatter( new IValueFormatter() {
//                @Override
//                public String getFormattedValue(float value, Entry entry, int dataSetIndex, ViewPortHandler viewPortHandler) {
//                    // 此处的value默认保存一位小数
//                    if (value==0) {
//                        return "";
//                    }
//                    return value + "";
//                }
//            });
                    sets.add(barDataSet1);

                    BarData barData = new BarData(sets);
                    barData.setBarWidth(0.2f); // 设置柱子的宽度
                    barChart.setData(barData);
                }
            }
            @Override
            public void onMyError(VolleyError error) {
            }
            @Override
            public void onImageSuccess(Bitmap bitmap) {
            }
        });
    }


    private void set(){
        /*折线饼状图*/
        System.out.println("折线图");
        mPieChart.setUsePercentValues(true); //设置是否使用百分值,默认不显示
        mPieChart.getDescription().setEnabled(false);
        mPieChart.setDragDecelerationFrictionCoef(0.95f);

        //是否设置中心文字
        mPieChart.setDrawCenterText(true);
        //绘制中间文字
        SpannableString sp = new SpannableString("个人剖析图");
        mPieChart.setCenterText(sp);
        mPieChart.setExtraOffsets(20.f, 0.f, 20.f, 0.f);

        //设置是否为实心图，以及空心时 中间的颜色
        mPieChart.setDrawHoleEnabled(true);
        mPieChart.setHoleColor(Color.WHITE);

        //设置圆环信息
        mPieChart.setTransparentCircleColor(Color.WHITE);//设置透明环颜色
        mPieChart.setTransparentCircleAlpha(110);//设置透明环的透明度
        mPieChart.setHoleRadius(55f);//设置内圆的大小
        mPieChart.setTransparentCircleRadius(60f);//设置透明环的大小

        mPieChart.setRotationAngle(0);
        // 触摸旋转
        mPieChart.setRotationEnabled(true);
        //选中变大
        mPieChart.setHighlightPerTapEnabled(true);

        //模拟数据
        ArrayList<PieEntry> entries = new ArrayList<PieEntry>();
        entries.add(new PieEntry(80, "颜值"));
        entries.add(new PieEntry(100, "智慧"));
        entries.add(new PieEntry(50, "身材"));
        entries.add(new PieEntry(50, "性格"));
        entries.add(new PieEntry(20, "声音"));

        //设置数据
        setData(entries);

        //默认动画
        mPieChart.animateY(1400, Easing.EasingOption.EaseInOutQuad);

        //设置图例
        Legend l = mPieChart.getLegend();
        //设置显示的位置，低版本用的是setPosition();
        l.setVerticalAlignment(Legend.LegendVerticalAlignment.BOTTOM);
        l.setHorizontalAlignment(Legend.LegendHorizontalAlignment.CENTER);
        //设置是否显示图例
        l.setDrawInside(false);
        l.setEnabled(true);

        // 输入图例标签样式
        mPieChart.setEntryLabelColor(Color.BLUE);
        mPieChart.setEntryLabelTextSize(18f);

    }

    //设置数据
    private void setData(ArrayList<PieEntry> entries) {
        PieDataSet dataSet = new PieDataSet(entries, "");
        //设置个饼状图之间的距离
        dataSet.setSliceSpace(0f);
        //颜色的集合，按照存放的顺序显示
        ArrayList<Integer> colors = new ArrayList<Integer>();
        for (int c : ColorTemplate.VORDIPLOM_COLORS)
            colors.add(c);
        for (int c : ColorTemplate.JOYFUL_COLORS)
            colors.add(c);
        for (int c : ColorTemplate.COLORFUL_COLORS)
            colors.add(c);
        for (int c : ColorTemplate.LIBERTY_COLORS)
            colors.add(c);
        for (int c : ColorTemplate.PASTEL_COLORS)
            colors.add(c);
        colors.add(ColorTemplate.getHoloBlue());
        dataSet.setColors(colors);

        //设置折线
        dataSet.setValueLinePart1OffsetPercentage(80.f);
        //设置线的长度
        dataSet.setValueLinePart1Length(0.3f);
        dataSet.setValueLinePart2Length(0.3f);
        //设置文字和数据图外显示
        dataSet.setXValuePosition(PieDataSet.ValuePosition.OUTSIDE_SLICE);
        dataSet.setYValuePosition(PieDataSet.ValuePosition.OUTSIDE_SLICE);

        PieData data = new PieData(dataSet);
        //百分比设置
        data.setValueFormatter(new PercentFormatter());
        //文字的颜色
        data.setValueTextSize(14f);
        data.setValueTextColor(Color.BLACK);
        mPieChart.setData(data);
        // 撤销所有的亮点
        mPieChart.highlightValues(null);
        mPieChart.invalidate();
    }
}
